package me.xue.communityhealth.admin.controller;

import me.xue.communityhealth.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class DepartmentController {

    private final DepartmentService departmentService;

    @Autowired
    public DepartmentController(DepartmentService departmentService) {
        this.departmentService = departmentService;
    }

    @GetMapping("/departments")
    public String departments(Model model) {
        List<String> departments = departmentService.findAll();
        model.addAttribute("departments", departments);
        return "departments";
    }

    @PostMapping("/department")
    @ResponseBody
    public String addDepartment(@RequestParam("department") String department) {
        if (StringUtils.isEmpty(department)) {
            return "部门名称不能为空";
        }
        int savedDepartment = departmentService.save(department);
        if (savedDepartment == 1) {
            return "success";
        }
        return "添加失败";
    }

    @DeleteMapping("/department/{departmentName}")
    @ResponseBody
    public String deleteDepartment(@PathVariable("departmentName") String department) {
        if (StringUtils.isEmpty(department)) {
            return "删除失败";
        }
        int deletedDepartment = departmentService.delete(department);
        if (deletedDepartment == 1) {
            return "success";
        }
        return "删除失败";
    }

}
